﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using RabbitMQServer.Huobi.Models;

namespace RabbitMQPublish
{
    public class HuobiPriceService
    {
        /// <summary>
        /// 所有价格
        /// </summary>
        /// <returns></returns>
        public static List<Prices> SetAll(Dictionary<string,string> names)
        {
                var url = "https://www.huobi.br.com/-/x/general/index/constituent_symbol/detail";
                var requesObj = GetRequestData(url, null, "GET");
                List<Prices> priceLogs = new List<Prices>();
                if (requesObj.hasData)
                {
                    foreach (var item in requesObj.data["data"]["symbols"])
                    {
                        if (names.ContainsKey(item["name"].ToString()))
                        {
                            var price = new Prices
                            {
                                close = (decimal)item["close"],
                                open = (decimal)item["open"],
                                rise_percent = (decimal)item["rise_percent"],
                                name = item["name"].ToString()
                            };
                            priceLogs.Add(price);
                        }
                    }
                }
                return priceLogs;
        }

        public static ResposeData GetRequestData(string url, string parameters = null, string method = "GET")
        {
            try
            {
                ResposeData resposeData = new ResposeData();
                if (method.ToLower() != "get" && method.ToLower() != "post") method = "GET";
                if (parameters != null && parameters != "" && method.ToLower() == "get")
                {
                    url += "?" + parameters;
                }
                Encoding charset = Encoding.GetEncoding("utf-8");
                HttpWebRequest request = null;
                if (url.IndexOf("https://") != -1)
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
                } 
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = method;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:57.0) Gecko/20100101 Firefox/57.0";
                //如果需要POST数据     
                if (parameters != null && parameters != "" && method.ToLower() == "post")
                {
                    byte[] data = charset.GetBytes(parameters);
                    using(Stream stream = request.GetRequestStream()) stream.Write(data, 0, data.Length);
                }
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using (Stream streams = response.GetResponseStream())
                {
                    StreamReader sr = new StreamReader(streams); //创建一个stream读取流  
                    string html = sr.ReadToEnd();   //从头读到尾，放到字符串html  
                    if (html != "")
                    {
                        resposeData.hasData = true;
                        resposeData.data = JObject.Parse(html);
                    }
                }
                return resposeData;
            }
            catch (Exception webEx)
            {
                Console.WriteLine(webEx.Message);
                return new ResposeData();//获取失败
            }            
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;  
        }
    }
    public class ResposeData
    {
        public bool hasData { get; set; }
        public JObject data { get; set; }

        public ResposeData()
        {
            this.hasData = false;
            this.data = new JObject();
        }
    }

}
